package com.cskaoyan.service.goods;

import com.cskaoyan.bean.comment.Comment;
import com.cskaoyan.bean.goods.*;
import com.cskaoyan.bo.goodsvo.GoodsCreateBo;
import com.cskaoyan.bo.goodsvo.GoodsUpdateBo;
import com.cskaoyan.mapper.goodsmapper.*;
import com.cskaoyan.vo.goodsvo.*;
import com.github.pagehelper.PageHelper;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;

import java.time.LocalDateTime;
import java.util.*;

@Service
public class GoodsServiceImpl implements GoodsService {
    @Autowired
    GoodsMapper goodsMapper;

    @Override
    public GoodsList_TotalVo query(Integer page, Integer limit, String sort, String order, String goodsSn, String name) {
        PageHelper.startPage(page, limit);

        GoodsExample goodsExample = new GoodsExample();
        GoodsExample.Criteria criteria = goodsExample.createCriteria();
        criteria.andDeletedEqualTo(false);
        goodsExample.setOrderByClause(sort + " " + order);

        if (goodsSn != null && goodsSn != ""){
            criteria.andGoodsSnEqualTo(goodsSn);
        }
        if(name != null && name != ""){
            criteria.andNameLike("%" + name + "%");
        }

        List<Goods> goods = goodsMapper.selectByExampleWithBLOBs(goodsExample);
        long total = goodsMapper.countByExample(goodsExample);

        GoodsList_TotalVo totalVo = new GoodsList_TotalVo();
        totalVo.setTotal(total);
        totalVo.setItems(goods);

        return totalVo;
    }

    @Autowired
    GoodsAttributeMapper goodsAttributeMapper;

    @Autowired
    GoodsProductMapper goodsProductMapper;

    @Autowired
    GoodsSpecificationMapper goodsSpecificationMapper;

    @Autowired
    GoodsCategoryMapper goodsCategoryMapper;

    /**
     * 更新商品时，获得详细信息
     */
    @Override
    public GoodsDetail_TotalVo detail(Integer id) {

        //用来接收Goods
        Goods goods = goodsMapper.selectByPrimaryKey(id);

        //用来接收List<Integer>
        GoodsDetail_CategoryIdsVo categoryIdsVo = goodsCategoryMapper.selectByPrimaryKey2(goods.getCategoryId());

        //用来接收attributes
        List<GoodsAttribute> attributesVo = goodsAttributeMapper.selectByGoodsId(id);

        //用来接收specification
        List<GoodsSpecification> goodsSpecifications = goodsSpecificationMapper.selectByGoodsId(id);

        //用来接收product
        List<GoodsProduct> goodsProducts = goodsProductMapper.selectByGoodsId(id);

        //用来接收返回值
        GoodsDetail_TotalVo goodsDetail_totalVo = new GoodsDetail_TotalVo();

        List<Integer> list = new ArrayList<>();
        if(categoryIdsVo != null){
            list.add(categoryIdsVo.getPid());
            list.add(categoryIdsVo.getId());
        }

        goodsDetail_totalVo.setCategoryIds(list);

        goodsDetail_totalVo.setGoods(goods);

        goodsDetail_totalVo.setAttributes(attributesVo);
        goodsDetail_totalVo.setSpecifications(goodsSpecifications);
        goodsDetail_totalVo.setProducts(goodsProducts);

        return goodsDetail_totalVo;
    }

    @Autowired
    GoodsBrandMapper goodsBrandMapper;

    @Override
    public Category_CategoryList_Vo catAndBrand() {
        //接受所有pid为零的
        List<Category_List_TotalVo> list = goodsCategoryMapper.selectByPidEql(0);

        //遍历上述数组为0,获得所有子类的
        for (Category_List_TotalVo categoryChildren : list) {
            int value = categoryChildren.getValue();
            List<Category_CategoryList_ChrildrenVo> children = goodsCategoryMapper.selectByPidEql2(value);
            categoryChildren.setChildren(children);
        }

        //获得brand相关信息
        List<Category_CategoryList_ChrildrenVo> brandList = goodsBrandMapper.selectById();

        //封装返回值
        Category_CategoryList_Vo category_categoryList_vo = new Category_CategoryList_Vo();
        category_categoryList_vo.setCategoryList(list);
        category_categoryList_vo.setBrandList(brandList);
        return category_categoryList_vo;
    }

    @Override
    public void
    update(GoodsUpdateBo goodsUpdateBo) {
        //针对goods做出修改
        Goods goods = goodsUpdateBo.getGoods();
        if(goods.getAddTime() == null){
            goods.setAddTime(new Date());
            goods.setUpdateTime(new Date());
            goods.setDeleted(false);
        }
        goodsMapper.updateByPrimaryKey(goods);

        //针对GoodsAttribute 作出修改
        List<GoodsAttribute> attributes = goodsUpdateBo.getAttributes();

        Integer[] list = goodsAttributeMapper.selectByGoodsId2(goods.getId());

        for (GoodsAttribute attribute : attributes) {
            //添加
            if(attribute.getGoodsId() == null){
                attribute.setGoodsId(goods.getId());
                attribute.setAddTime(new Date());
                attribute.setUpdateTime(new Date());
                goodsAttributeMapper.insert(attribute);
            }else{
                //更新
                for (int i = 0; i < list.length; i++) {
                    if(attribute.getId() == list[i]){
                        list[i] = 0;
                    }
                }
            }
        }
        for (int i = 0; i < list.length; i++) {
            if(list[i]!=0){
                goodsAttributeMapper.updateByPrimaryKey2(list[i]);
            }
        }

        //针对Specification作出修改
        List<GoodsSpecification> specifications = goodsUpdateBo.getSpecifications();

        Integer[] list4 = goodsSpecificationMapper.selectByGoodsId2(goods.getId());

        for (GoodsSpecification specification : specifications) {
            if(specification.getGoodsId() == null){
                specification.setGoodsId(goods.getId());
                specification.setUpdateTime(new Date());
                specification.setAddTime(new Date());
                specification.setDeleted(false);
                goodsSpecificationMapper.insert(specification);
            } else if(list4.length > 0){
                for (int i = 0; i < list4.length; i++) {
                    if(specification.getId() == list4[i]){
                        list[i] = 0;
                    }
                }
            }
        }

        for (int i = 0; i < list.length; i++) {
            if(list[i]!=0){
                goodsSpecificationMapper.updateByPrimaryKey2(list[i]);
            }
        }

        //针对product作出修改
        List<GoodsProduct> products = goodsUpdateBo.getProducts();
            //删除该id下所有的货品规格
        GoodsProductExample goodsProductExample = new GoodsProductExample();
        GoodsProductExample.Criteria criteria = goodsProductExample.createCriteria();
        criteria.andGoodsIdEqualTo(goods.getId());
        goodsProductMapper.deleteByExample(goodsProductExample);
            //重新插入
        for (GoodsProduct product : products) {
            product.setId(null);
            product.setGoodsId(goods.getId());
            product.setAddTime(new Date());
            product.setUpdateTime(new Date());
            product.setDeleted(false);
            goodsProductMapper.insertSelective(product);
        }
    }

    @Override
    public Integer create(GoodsCreateBo goodsCreateBo) {

        GoodsExample goodsExample = new GoodsExample();
        GoodsExample.Criteria criteria = goodsExample.createCriteria();
        criteria.andGoodsSnEqualTo(goodsCreateBo.getGoods().getGoodsSn());
        if(goodsMapper.countByExample(goodsExample) != 0){
            return 0;
        }

        //处理goods
        Goods goods = goodsCreateBo.getGoods();
        goods.setAddTime(new Date());
        goods.setUpdateTime(new Date());
        goods.setDeleted(false);
        goodsMapper.insert2(goods);
            //用于获取新插入数据的id
        Integer id = goods.getId();

        //specifications
        List<GoodsSpecification> specifications = goodsCreateBo.getSpecifications();
        for (GoodsSpecification specification : specifications) {
            specification.setGoodsId(id);
            specification.setUpdateTime(new Date());
            specification.setAddTime(new Date());
            specification.setDeleted(false);
            goodsSpecificationMapper.insert(specification);
        }

        //products
        List<GoodsProduct> products = goodsCreateBo.getProducts();
        for (GoodsProduct product : products) {
            product.setId(null);
            product.setGoodsId(id);
            product.setAddTime(new Date());
            product.setUpdateTime(new Date());
            product.setDeleted(false);
            goodsProductMapper.insertSelective(product);
        }
        //attributes
        List<GoodsAttribute> attributes = goodsCreateBo.getAttributes();
        for (GoodsAttribute attribute : attributes) {
            attribute.setGoodsId(id);
            attribute.setAddTime(new Date());
            attribute.setUpdateTime(new Date());
            attribute.setDeleted(false);
            goodsAttributeMapper.insert(attribute);
        }
        return 1;
    }

    @Override
    public void delete(Goods goods) {
        goods.setUpdateTime(new Date());
        goods.setDeleted(true);
        goodsMapper.updateByPrimaryKey(goods);
    }

    @Autowired
    GoodsCommentMapper goodsCommentMapper;

    /**
     * 获取商品评论信息
     */
    @Override
    public GoodsComment_TotalVo queryComment(Integer page, Integer limit, String sort, String order, Integer userId, Integer valueId) {
        //开始分页
        PageHelper.startPage(page,limit);

        GoodsCommentExample goodsCommentExample = new GoodsCommentExample();
        goodsCommentExample.setOrderByClause(sort + " " + order);
        GoodsCommentExample.Criteria criteria = goodsCommentExample.createCriteria();
        criteria.andDeletedEqualTo(false);
        //这里不用添加(userId != "")
        if(userId != null){
            criteria.andUserIdEqualTo(userId);
        }

        if(valueId != null){
            criteria.andValueIdEqualTo(valueId);
        }

        List<GoodsComment> goodsComments = goodsCommentMapper.selectByExample(goodsCommentExample);

        long total = goodsCommentMapper.countByExample(goodsCommentExample);

        GoodsComment_TotalVo comment_totalVo = new GoodsComment_TotalVo();
        comment_totalVo.setTotal(total);
        comment_totalVo.setItems(goodsComments);

        return comment_totalVo;
    }

    /**
     * kd 微信小程序-商品页面-获得评论列表
     */
    @Override
    public List<GoodsComment> queryComment(Integer page, Integer limit, Byte type, Integer valueId) {

        PageHelper.startPage(page,limit);
        GoodsCommentExample goodsCommentExample = new GoodsCommentExample();
        GoodsCommentExample.Criteria criteria = goodsCommentExample.createCriteria();
        criteria.andDeletedEqualTo(false).andValueIdEqualTo(valueId).andTypeEqualTo(type);
        return goodsCommentMapper.selectByExample(goodsCommentExample);
    }

    /**
     * kd 微信小程序-商品页面-评论页面-统计所有评论数量和带有图片的评论数量
     */
    @Override
    public Map<String, Integer> queryCommentCount(Integer valueId, Byte type) {
        GoodsCommentExample goodsCommentExample = new GoodsCommentExample();
        GoodsCommentExample.Criteria criteria = goodsCommentExample.createCriteria();
        criteria.andDeletedEqualTo(false).andValueIdEqualTo(valueId).andTypeEqualTo(type);
        List<GoodsComment> allGoodsComments = goodsCommentMapper.selectByExample(goodsCommentExample);
        criteria.andHasPictureEqualTo(true);
        List<GoodsComment> allGoodsCommentsWithPic = goodsCommentMapper.selectByExample(goodsCommentExample);
        Map<String, Integer> count = new HashMap<>();
        count.put("allCount",allGoodsComments.size());
        count.put("hasPicCount",allGoodsCommentsWithPic.size());
        return count;
    }



    @Override
    public Comment insertComment(Comment comment) {
        comment.setAddTime(LocalDateTime.now());
        comment.setUpdateTime(LocalDateTime.now());
        goodsMapper.insertComment(comment);
        return comment;
    }

    /**
     * 删除商品
     */
    @Override
    public void deleteComment(GoodsComment comment) {
        comment.setUpdateTime(new Date());
        comment.setDeleted(true);
        goodsCommentMapper.updateByPrimaryKey(comment);
    }


}
